"""
@Author    : ghenyar
@Time      : 2025/8/28 12:33
@File      : response.py
@Desc      : 统一返回
"""
from typing import Union, Optional, TypeVar, Generic, Dict, List, Any

from pydantic import BaseModel

from app.common.page_result import PageResult

T = TypeVar("T")  # 泛型，用于表示任意类型


class ApiResponse(BaseModel, Generic[T]):
    code: int = 200
    status: int = 0
    message: str
    data: Optional[Union[T, Dict, List, str]] = None

    @classmethod
    def result(cls, data: Union[T] = None, message: Optional[str] = "操作成功"):
        """
        返回数据
        :param data: 返回的数据
        :param message: 操作提示信息
        :return: Response 对象
        """
        return cls(data=data, message=message)

    @classmethod
    def success(cls, message: Optional[str] = "操作成功", code: Optional[int] = 200):
        """
        返回成功响应
        :param message: 操作提示信息
        :param code: HTTP 状态码，默认 200
        :return: Response 对象
        """
        return cls(message=message, code=code)

    @classmethod
    def failed(cls, message: Optional[str] = "操作失败", code: Optional[int] = 400):
        """
        返回失败响应
        :param message: 操作提示信息
        :param code: HTTP 状态码，默认 400
        :return: Response 对象
        """
        return cls(code=code, message=message, status=-1)

    @classmethod
    def page_list(cls, data:PageResult):
        """
        返回分页数据
        :param data: 数据
        :return: Response 对象，包含分页数据
        """
        page_data = {
            "list": data.items,
            "total": data.total,
            "page": data.page,
            "pageSize": data.page_size,
            "totalPages": data.total_pages,
        }
        return cls.result(data=page_data)

    @staticmethod
    def exception_response(*,
                           code: int = 200,
                           message: str = "操作成功",
                           data: Any = None,
                           status: int = 0):
        result = {
            "code": code,
            "status": status,
            "message": message,
        }
        if data:
            result["data"] = data
        return result
